package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.PurchaseOrder;
import com.geek.factory.entity.PurchaseOrderDetail;
import com.geek.factory.entity.Supplier;
import com.geek.factory.result.Result;
import com.geek.factory.service.IPurchaseOrderService;
import com.geek.factory.service.IPurchaseOrderDetailService;
import com.geek.factory.service.SupplierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购单管理控制器
 */
@RestController
@RequestMapping("/purchase-order")
@Api(tags = "后台系统的 - 采购单模块")
@Slf4j
@CrossOrigin
public class PurchaseOrderController {

    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    
    @Autowired
    private IPurchaseOrderDetailService purchaseOrderDetailService;
    
    @Autowired
    private SupplierService supplierService;

    /**
     * 生成采购单编码
     */
    private String generatePurchaseOrderCodeInternal() {
        String prefix = "PO";  // PO = Purchase Order
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }

    @ApiOperation("生成采购单编码")
    @GetMapping("/generate-code")
    public Result generatePurchaseOrderCode() {
        try {
            String orderNo = generatePurchaseOrderCodeInternal();
            Map<String, String> result = new HashMap<>();
            result.put("orderNo", orderNo);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成采购单编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败");
        }
    }

    @ApiOperation("通过ID查询采购单信息")
    @GetMapping("/{orderId}")
    public Result findPurchaseOrderById(@ApiParam("采购单ID") @PathVariable("orderId") Integer orderId) {
        try {
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(orderId);
            if (purchaseOrder == null) {
                return new Result(SuccessConstant.FAIL, "采购单不存在");
            }
            
            // 获取供应商信息
            if (purchaseOrder.getSupplierId() != null) {
                Supplier supplier = supplierService.getById(purchaseOrder.getSupplierId());
                if (supplier != null) {
                    purchaseOrder.setSupplierName(supplier.getSupplierName());
                }
            }
            
            // 获取采购单明细
            QueryWrapper<PurchaseOrderDetail> detailWrapper = new QueryWrapper<>();
            detailWrapper.eq("purchase_id", orderId);
            List<PurchaseOrderDetail> details = purchaseOrderDetailService.list(detailWrapper);
            
            // 计算总金额（如果为空或为0）
            if (purchaseOrder.getAmount() == null || purchaseOrder.getAmount().compareTo(BigDecimal.ZERO) == 0) {
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (PurchaseOrderDetail detail : details) {
                    if (detail.getAmount() != null) {
                        totalAmount = totalAmount.add(detail.getAmount());
                    } else if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
                        BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                        totalAmount = totalAmount.add(amount);
                    }
                }
                
                // 更新采购单总金额
                if (totalAmount.compareTo(BigDecimal.ZERO) > 0 && 
                    (purchaseOrder.getAmount() == null || purchaseOrder.getAmount().compareTo(totalAmount) != 0)) {
                    purchaseOrder.setAmount(totalAmount);
                    purchaseOrderService.updateById(purchaseOrder);
                }
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("order", purchaseOrder);
            result.put("details", details);
            
            return new Result(SuccessConstant.SUCCESS, "ok", result);
        } catch (Exception e) {
            log.error("查询采购单失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    // 新增采购单
    @ApiOperation("新增采购单")
    @PostMapping
    public Result addPurchaseOrder(@RequestBody PurchaseOrder purchaseOrder) {
        try {
            // 如果没有设置采购单编码，自动生成
            if (purchaseOrder.getOrderNo() == null || purchaseOrder.getOrderNo().trim().isEmpty()) {
                purchaseOrder.setOrderNo(generatePurchaseOrderCodeInternal());
            }
    
            // 设置默认值
            if (purchaseOrder.getCreatedTime() == null) {
                purchaseOrder.setCreatedTime(LocalDateTime.now());
            }
            if (purchaseOrder.getCreatedBy() == null || purchaseOrder.getCreatedBy().trim().isEmpty()) {
                purchaseOrder.setCreatedBy("admin");
            }
            
            // 如果设置了供应商ID但没有供应商名称，查询供应商名称
            if (purchaseOrder.getSupplierId() != null && 
                (purchaseOrder.getSupplierName() == null || purchaseOrder.getSupplierName().isEmpty())) {
                Supplier supplier = supplierService.getById(purchaseOrder.getSupplierId());
                if (supplier != null) {
                    purchaseOrder.setSupplierName(supplier.getSupplierName());
                }
            }
            
            // 确保金额不为null
            if (purchaseOrder.getAmount() == null) {
                purchaseOrder.setAmount(BigDecimal.ZERO);
            }
    
            boolean isSuccess = purchaseOrderService.save(purchaseOrder);
            log.info("新增采购单: {}, 结果: {}", purchaseOrder, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "新增成功", purchaseOrder);
            }
            return new Result(SuccessConstant.FAIL, "新增失败");
        } catch (Exception e) {
            log.error("新增采购单失败", e);
            return new Result(SuccessConstant.FAIL, "新增失败: " + e.getMessage());
        }
    }

    // 根据ID删除采购单
    @ApiOperation("根据ID删除采购单")
    @DeleteMapping("/{orderId}")
    public Result deletePurchaseOrder(@ApiParam("采购单ID") @PathVariable("orderId") Integer orderId) {
        boolean isSuccess = purchaseOrderService.removeById(orderId);
        log.info("删除采购单ID: {}, 结果: {}", orderId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    // 修改采购单信息
    @ApiOperation("修改采购单信息")
    @PutMapping("/{orderId}")
    public Result updatePurchaseOrder(@ApiParam("采购单ID") @PathVariable("orderId") Integer orderId, @RequestBody PurchaseOrder purchaseOrder) {
        try {
            purchaseOrder.setOrderId(orderId);
            
            // 如果设置了供应商ID但没有供应商名称，查询供应商名称
            if (purchaseOrder.getSupplierId() != null && 
                (purchaseOrder.getSupplierName() == null || purchaseOrder.getSupplierName().isEmpty())) {
                Supplier supplier = supplierService.getById(purchaseOrder.getSupplierId());
                if (supplier != null) {
                    purchaseOrder.setSupplierName(supplier.getSupplierName());
                }
            }
            
            boolean isSuccess = purchaseOrderService.updateById(purchaseOrder);
            log.info("修改采购单: {}, 结果: {}", purchaseOrder, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "修改成功", purchaseOrder);
            }
            return new Result(SuccessConstant.FAIL, "修改失败");
        } catch (Exception e) {
            log.error("修改采购单失败", e);
            return new Result(SuccessConstant.FAIL, "修改失败: " + e.getMessage());
        }
    }

    @ApiOperation("分页查询采购单列表")
    @GetMapping("/page")
    public Result getPurchaseOrderPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String supplierName
    ) {
        try {
            QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(orderNo)) {
                wrapper.like("order_no", orderNo);
            }
            if (StringUtils.isNotBlank(supplierName)) {
                wrapper.like("supplier_name", supplierName);
            }
            wrapper.orderByDesc("created_time");
    
            Page<PurchaseOrder> page = purchaseOrderService.page(new Page<>(current, size), wrapper);
            
            // 丰富采购单信息
            for (PurchaseOrder order : page.getRecords()) {
                // 确保供应商名称存在
                if (order.getSupplierId() != null && 
                    (order.getSupplierName() == null || order.getSupplierName().isEmpty())) {
                    Supplier supplier = supplierService.getById(order.getSupplierId());
                    if (supplier != null) {
                        order.setSupplierName(supplier.getSupplierName());
                    }
                }
                
                // 确保金额正确
                if (order.getAmount() == null || order.getAmount().compareTo(BigDecimal.ZERO) == 0) {
                    // 查询采购单明细
                    QueryWrapper<PurchaseOrderDetail> detailWrapper = new QueryWrapper<>();
                    detailWrapper.eq("purchase_id", order.getOrderId());
                    List<PurchaseOrderDetail> details = purchaseOrderDetailService.list(detailWrapper);
                    
                    // 计算总金额
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    for (PurchaseOrderDetail detail : details) {
                        if (detail.getAmount() != null) {
                            totalAmount = totalAmount.add(detail.getAmount());
                        } else if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
                            BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                            totalAmount = totalAmount.add(amount);
                        }
                    }
                    
                    // 更新采购单总金额
                    if (totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                        order.setAmount(totalAmount);
                        purchaseOrderService.updateById(order);
                    }
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("records", page.getRecords());
            data.put("total", page.getTotal());
            data.put("current", page.getCurrent());
            data.put("size", page.getSize());
            data.put("pages", page.getPages());
    
            return new Result(SuccessConstant.SUCCESS, "查询成功", data);
        } catch (Exception e) {
            log.error("分页查询采购单失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取所有采购单列表")
    @GetMapping("/list")
    public Result getAllPurchaseOrders() {
        try {
            List<PurchaseOrder> purchaseOrders = purchaseOrderService.list();
            
            // 丰富采购单信息
            for (PurchaseOrder order : purchaseOrders) {
                // 确保供应商名称存在
                if (order.getSupplierId() != null && 
                    (order.getSupplierName() == null || order.getSupplierName().isEmpty())) {
                    Supplier supplier = supplierService.getById(order.getSupplierId());
                    if (supplier != null) {
                        order.setSupplierName(supplier.getSupplierName());
                    }
                }
            }
            
            return new Result(SuccessConstant.SUCCESS, "查询成功", purchaseOrders);
        } catch (Exception e) {
            log.error("获取所有采购单列表失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("更新采购单总金额")
    @PostMapping("/{orderId}/update-amount")
    public Result updateOrderAmount(@PathVariable Integer orderId) {
        try {
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(orderId);
            if (purchaseOrder == null) {
                return new Result(SuccessConstant.FAIL, "采购单不存在");
            }
            
            // 查询采购单明细
            QueryWrapper<PurchaseOrderDetail> detailWrapper = new QueryWrapper<>();
            detailWrapper.eq("purchase_id", orderId);
            List<PurchaseOrderDetail> details = purchaseOrderDetailService.list(detailWrapper);
            
            // 计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (PurchaseOrderDetail detail : details) {
                if (detail.getAmount() != null) {
                    totalAmount = totalAmount.add(detail.getAmount());
                } else if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
                    BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                    totalAmount = totalAmount.add(amount);
                    
                    // 更新明细金额
                    detail.setAmount(amount);
                    purchaseOrderDetailService.updateById(detail);
                }
            }
            
            // 更新采购单总金额
            purchaseOrder.setAmount(totalAmount);
            purchaseOrderService.updateById(purchaseOrder);
            
            return new Result(SuccessConstant.SUCCESS, "更新成功", purchaseOrder);
        } catch (Exception e) {
            log.error("更新采购单总金额失败", e);
            return new Result(SuccessConstant.FAIL, "更新失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取采购订单状态统计")
    @GetMapping("/status-stats")
    public Result getPurchaseOrderStatusStats() {
        try {
            Map<String, Long> stats = purchaseOrderService.getPurchaseOrderStatusStats();
            return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
        } catch (Exception e) {
            log.error("获取采购订单状态统计失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败");
        }
    }
}